<!--
 * @Descripttion: 
 * @Author: Kevin
 * @Date: 2022-06-14 10:58:57
 * @LastEditors: Tommy Chen
 * @LastEditTime: 2024-07-13
-->
<template>
  <div>
    <a-form-model
      :labelCol="{ span: 10 }"
      :wrapperCol="{ span: 14 }"
      labelAlign="left"
      :model="authForm"
      ref="authFormRef"
      :rules="ruleObj"
      :colon="false"
      style="width: 600px"
    >
      <a-form-model-item prop="name" :label="$t('quickCreate.ruleName')">
        <a-input v-model="authForm.name" :placeholder="$t('common.inuptTip')" />
      </a-form-model-item>
      <a-form-model-item
        v-if="['portal', 'dot1xWireless'].includes(formType)"
        :label="$t('quickCreate.condition')"
        prop="type"
      >
        <a-radio-group v-model="authForm.networkType">
          <a-radio value="all">{{ $t('quickCreate.allSsid') }} </a-radio>
          <a-radio value="ssid">{{ $t('quickCreate.selSsid') }} </a-radio>
        </a-radio-group>
      </a-form-model-item>

      <!-- 手动输入的VLAN -->
      <div
        class="row"
        v-for="(item, index) in authForm.ssidObjList"
        :key="'ssid' + index"
        v-show="authForm.networkType === 'ssid'"
      >
        <div class="col">
          <a-form-model-item
            style="width: 100%"
            :prop="'ssidObjList.' + index + '.value'"
            :rules="[
              {
                validator: validateSsid,
                trigger: 'blur',
              },
            ]"
          >
            <a-input
              v-model="item.value"
              :placeholder="$t('quickCreate.ssidEnter')"
            ></a-input>
          </a-form-model-item>
        </div>
        <div class="col">
          <div class="icon-box">
            <a-icon
              type="delete"
              v-if="authForm.ssidObjList.length > 1"
              @click="onDeleteSsidItem(item, index)"
            />
            <a-icon
              type="plus"
              v-if="index + 1 == authForm.ssidObjList.length && index + 1 < 8"
              @click="onAddSsidItem"
            />
          </div>
        </div>
      </div>

      <a-form-model-item
        v-if="['portal'].includes(formType)"
        :label="$t('gwAuthentication.nonAuth')"
      >
        <a-switch @change="onChangeSeamless" v-model="authForm.isSeamless" />
      </a-form-model-item>
      <a-form-model-item
        v-if="['portal'].includes(formType)"
        :label="$t('portalAuth.seamlessPeriod')"
        v-show="authForm.isSeamless"
      >
        <a-select v-model="authForm.seamless">
          <a-select-option :value="2">
            {{ $t('gwAuthentication.day') }}
          </a-select-option>
          <a-select-option :value="3">
            {{ $t('gwAuthentication.week') }}
          </a-select-option>
          <a-select-option :value="4">
            {{ $t('gwAuthentication.month') }}
          </a-select-option>
          <a-select-option :value="5">
            {{ $t('gwAuthentication.foreve') }}
          </a-select-option>
        </a-select>
      </a-form-model-item>
    </a-form-model>
  </div>
</template>

<script>
import lodash from 'lodash';
import { ValiDateTools } from '@/utils/validateTools';
export default {
  name: 'authForm',
  components: {},
  props: {
    record: {
      typeof: Object,
      default: () => {
        return null;
      },
    },
    formType: {
      typeof: String,
      default: () => {
        return 'portal';
      },
    },
  },
  data() {
    return {
      authForm: {
        name: '', // 认证规则名称,
        authModeType: 1, // 认证方式 1：portal，2：802.1X有线，3：802.1X无线
        networkType: 'all', // all：所有；ssid：指定 SSID；vlan：指定 Vlan；ip：指定 IP 段；ssid_vlan：指定 SSID + Vlan
        isSeamless: true,
        seamless: 2,
        ssidObjList: [
          {
            value: '',
          },
        ],
      },

      ruleObj: {
        name: [
          {
            min: 1,
            max: 64,
            message: this.$t('common.byteRange', [64]),
            trigger: 'blur',
          },
          {
            required: true,
            message: this.$t('common.mustEnter'),
            trigger: 'blur',
          },
          {
            validator: this.validateName,
            trigger: 'blur',
          },
        ],
        networkType: [
          {
            required: true,
            trigger: 'change',
          },
        ],
      },
    };
  },
  watch: {
    formType: {
      handler(value) {
        switch (value) {
          case 'dot1xWired':
            this.authForm.authModeType = 2;
            break;
          case 'dot1xWireless':
            this.authForm.authModeType = 3;
            break;
          case 'portal':
          default:
            this.authForm.authModeType = 1;
        }
      },
      immediate: true,
    },
    record: {
      handler(value) {
        if (value) {
          this.authForm = lodash.cloneDeep(value);
          delete this.authForm.accountSourceList;
          delete this.authForm.areaList;
          delete this.authForm.networkInfoList;
          if (this.authForm.seamless === 0) {
            this.$set(this.authForm, 'isSeamless', false);
          } else {
            this.$set(this.authForm, 'isSeamless', true);
          }
          value.networkInfoList = value.networkInfoList || [];
          this.$set(
            this.authForm,
            'ssidObjList',
            value.networkInfoList.map((item) => {
              return { value: item.ssid };
            })
          );
        }
      },
      deep: true,
      immediate: true,
    },
  },
  methods: {
    validateName(rule, value, callback) {
      if (ValiDateTools.isEmojiCharacter(value)) {
        return callback(new Error(this.$t('common.notEnterEmoji')));
      }

      return callback();
    },
    validateSsid(rule, value, callback) {
      // const { result, msg } = ValiDateTools.checkSsidName(value);
      // if (!result) {
      //   return callback(new Error(msg));
      // }
      if (this.authForm.networkType === 'all') {
        return callback();
      }
      if (!value) {
        return callback(new Error(this.$t('common.mustEnter')));
      }
      if (value.length > 64) {
        return callback(new Error(this.$t('common.byteRange', [64])));
      }
      if (ValiDateTools.isEmojiCharacter(value)) {
        return callback(new Error(this.$t('common.notEnterEmoji')));
      }
      const uniqueArray = lodash.uniqBy(this.authForm.ssidObjList, 'value');
      const hasDuplicates =
        this.authForm.ssidObjList.length !== uniqueArray.length;
      if (hasDuplicates) {
        return callback(new Error(this.$t('common.ssidNotRepeat', [64])));
      }

      return callback();
    },
    resetForm() {
      const authModeType = this.authForm.authModeType;
      this.authForm = {
        name: '', // 认证规则名称,
        authModeType, // 认证方式 1：portal，2：802.1X有线，3：802.1X无线
        networkType: 'all', // all：所有；ssid：指定 SSID；vlan：指定 Vlan；ip：指定 IP 段；ssid_vlan：指定 SSID + Vlan
        isSeamless: true,
        seamless: 2,
        ssidObjList: [
          {
            value: '',
          },
        ],
      };
    },
    onChangeSeamless(checked) {
      if (checked && this.authForm.seamless === 0) {
        this.authForm.seamless = 2;
      }
    },

    // 校验IP
    onAddSsidItem() {
      this.authForm.ssidObjList.push({
        value: '',
      });
    },
    onDeleteSsidItem(item, index) {
      this.authForm.ssidObjList.splice(index, 1);
    },
    getModel() {
      return new Promise((resolve) => {
        this.$refs.authFormRef.validate((valid) => {
          if (!valid) {
            resolve(null);
            return false;
          }

          const res = lodash.cloneDeep(this.authForm);
          if (!res.isSeamless) {
            res.seamless = 0;
          }
          res.ssidList = res.ssidObjList.map((item) => {
            return item.value;
          });
          delete res.ssidObjList;

          resolve(res);
        });
      });
    },
  },
};
</script>

<style lang="less" scoped>
/deep/.ant-form-item {
  margin-bottom: 8px;
}
.row {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-left: 42%;
  width: 376px;
  margin-bottom: 12px;
  /deep/.ant-input {
    width: 350px;
  }
  .icon-box {
    display: flex;
    align-items: center;
    height: 36px;
    gap: 8px;
    width: 36px;
    margin-left: 60px;
  }
  /deep/ .ant-form-item {
    flex: auto;
    margin: auto 0;
  }
  /deep/.ant-col-14 {
    width: 100%;
  }
  .col {
    display: flex;
    // justify-content: center;
    align-items: center;
    line-height: 40px;
    &:nth-child(1) {
      width: 80%;
    }
  }
}
</style>
